package offerbook.Code28_recallback_回溯_N皇后_排列;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created at 2019/10/22 0022 下午 4:54
 * --求字符串的全排列
 *
 * ---重复的可以重复排
 *
 * ---重复的不可重复排
 */
public class Code28_FullPermutation {


    public static List<String> permutation(String s){
        List<String> res = new ArrayList<>();
        //注意返回应该是[]不是null
        if(s == null || s.length() == 0){
            return res;
        }

      //  process1(s.toCharArray(),0,res);
        process2(s.toCharArray(),0,res);
        return res;
    }

    private static void process1(char[] chars, int index, List<String> res) {
        if(index == chars.length - 1){
            res.add(String.valueOf(chars));
            return;
        }
        for (int i = index; i < chars.length; i++) {
            swap(chars, index, i);
            process1(chars,index+1,res);
            swap(chars, index, i);
        }
    }

    private static void process2(char[] chars, int index, List<String> res) {
        if(index == chars.length - 1){
            res.add(String.valueOf(chars));
            return;
        }
        Set<Character> set = new HashSet<>();
        for (int i = index; i < chars.length; i++) {
            if(!set.contains(chars[i])) {
                set.add(chars[i]);
                swap(chars, index, i);
                process2(chars,index+1,res);
                swap(chars, index, i);
            }
        }
    }

    private static void swap(char[] chars, int index, int i) {
        char temp = chars[index];
        chars[index] = chars[i];
        chars[i] = temp;
    }

    public static void main(String[] args) {
        List<String> list = permutation("aaa");
        list.forEach(System.out::println);

    }

}
